//
//  EeLoopView.swift
//  housingResources
//
//  Created by zhu xietong on 2017/7/25.
//  Copyright © 2017年 节操君. All rights reserved.
//

import UIKit
import Eelay
@objc public protocol EeActionDelegate
{
    func active(onwer:Any,actionID:String,data:NSMutableDictionary)
}

open class EeKit:JoView{
    public weak var deletate:EeActionDelegate?
}

open class EeLoopView<T:EeKit>: JoView,UIScrollViewDelegate,EeActionDelegate {
    open func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
        
    }

    public var timer:SwiftTimer?

    public let scrollView = UIScrollView()
    public let pageControl = UIPageControl()
    public var imgIndexOf = 0
    public weak var deletate:EeActionDelegate?
    
    public var selectAction:(Int,NSMutableDictionary) ->Void = {_,_  in}
    
    public var placeholderImg:UIImage?
    public var oldContentOffsetX:CGFloat = 0.0
    public var interval:TimeInterval = 5
    
    typealias ContentView = T
    
    public var datas:NSMutableArray?{
        didSet{
            
            if let us = datas
            {
                let list = NSMutableArray()
                us.list{ (one:NSMutableDictionary, i) in
                    list.add(one)
                }
                
                if us.count > 1
                {
                    list.add(us.firstObject!)
                }
                self.listCount = list.count
                self.load(list: list)
            }
            else
            {
                self.listCount = 0
                self.load(list:  NSMutableArray())
            }
        }
    }
    
    public var page:Int{
        get{
            return self.pageControl.currentPage
        }
        set{
            self.pageControl.currentPage = newValue
            scrollView.setContentOffset([(self.pageControl.currentPage.cg_floatValue)*self.frame.width, 0], animated: false)
        }
    }
    
    
    
    var listCount:Int = 0
    
    public var autoScroll = true
    convenience required public init() {
        self.init(frame:[0,0])
    }
    
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    override open func addLayoutRules() {
        self.pageControl.currentPage = 0;
        self.pageControl.currentPageIndicatorTintColor = UIColor.main_color
        self.pageControl.pageIndicatorTintColor = UIColor(shex: "#ccc")
        
        scrollView.contentOffset = [0, 0]
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.isPagingEnabled = true
        self.imgIndexOf = 1;
        scrollView.delegate = self;
        
        addSubview(scrollView)
        addSubview(pageControl)
        
        layoutScrollView()
    }
    
    
    open func layoutScrollView() {
        self.eelay = [
            [scrollView,[ee.T.L.B.R,[0.+1000,0.+1000,0.+1000,0.+1000]]],
            [pageControl,[ee.X],[ee.B]]
        ]
    }
    
    
    func updatePage(index:Int) {
        let oldP = pageControl.currentPage
        let newP = index
        if oldP != newP
        {
            pageControl.currentPage = newP
            
            if let list = datas
            {
                if list.count > index
                {
                    if let obj = list[newP] as? NSMutableDictionary
                    {
                        self.deletate?.active(onwer: self, actionID: "scrollTo[\(index)]", data: obj)
                    }
                }
            }
        }
    }
    
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if let _ = self.datas
        {
            let point = scrollView.contentOffset
            let isRight = oldContentOffsetX < point.x
            oldContentOffsetX = point.x
            
            if (point.x > self.frame.width*(self.listCount.cg_floatValue-2)+self.frame.width*0.5) && (self.timer == nil)
            {
                updatePage(index: 0)
            }
            else if (point.x > self.frame.width*(self.listCount.cg_floatValue-2))&&(self.timer != nil)&&isRight{
                updatePage(index: 0)
            }
            else{
                let newP = Int((point.x + self.frame.width*0.5) / self.frame.width)
                updatePage(index: newP)
            }
            if (point.x >= self.frame.width*(self.listCount.cg_floatValue-1)) {
                scrollView.setContentOffset([self.frame.width+point.x-self.frame.width*self.listCount.cg_floatValue, 0], animated: false)
                
            }else if (point.x < 0) {
                scrollView.setContentOffset([point.x+self.frame.width*(self.listCount.cg_floatValue-1), 0], animated: false)
            }
        }
        
    }
    
    public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        stopTimer()
    }
    
    public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        startTimer()
    }
    
    func startTimer() {
        if autoScroll
        {
            weak var wself = self
            self.timer = SwiftTimer(interval: .seconds(Int(interval)), repeats: true, queue: .main, handler: { (timer) in
                wself?.nextPage()
            })
            //            self.timer = Timer(timeInterval: interval, repeats: true) { (timer) in
            //                wself?.nextPage()
            //            }
            //            RunLoop.current.add(self.timer!, forMode: RunLoopMode.commonModes)
            
            timer?.start()
//            self.timer = Timer(timeInterval: interval, target: self, selector: #selector(nextPage), userInfo: nil, repeats: true)
//            RunLoop.current.add(self.timer!, forMode: RunLoopMode.commonModes)
        }
    }
    
    
    func stopTimer() {
        
        self.timer = nil
    }
    
    @objc func nextPage() {
        if listCount > 1
        {
            scrollView.setContentOffset([(self.pageControl.currentPage.cg_floatValue+1)*self.frame.width, 0], animated: true)
        }
    }
    
    func load(list:NSMutableArray){
        
        let vs  = scrollView.subviews
        for v in vs
        {
            v.removeFromSuperview()
        }
        
        var preView:ContentView?
        
        
        for one in list
        {
            let imageView = ContentView()
            imageView.deletate = self
            if let dict = one as? NSMutableDictionary{
                imageView.mo.model = dict
            }
            
            scrollView.eelay = [
                [imageView,[ee.width.height],[ee.T.B]],
            ]
            

            
            if let p = preView
            {
                scrollView.eelay = [
                    [imageView,[p,ee.R,ee.L]]
                ]
            }
            else{
                scrollView.eelay = [
                    [imageView,[ee.L]],
                ]
            }
            imageView.clipsToBounds = true
            preView = imageView
        }
        
        if let p = preView
        {
            scrollView.eelay = [
                [p,[ee.R]],
            ]

        }
        
        self.pageControl.numberOfPages = listCount - 1;
        stopTimer()
        addClick()
        startTimer()
        self.clipsToBounds = true
    }
    
    func addClick(){
        let tap = UITapGestureRecognizer(target: self, action: #selector(imgClick))
        scrollView.addGestureRecognizer(tap)
    }
    
    @objc func imgClick() {
        let index = pageControl.currentPage
        if let list = datas
        {
            if list.count > index
            {
                if let obj = list[index] as? NSMutableDictionary
                {
                    self.deletate?.active(onwer: self, actionID: "tap[\(index)]", data: obj)
                }
            }
        }
    }

    
    open override var intrinsicContentSize: CGSize
    {
        return self.frame.size
    }
    
    
    
    deinit {
        stopTimer()
    }
    
}
